/**
 * Created by hldev on 17-2-14.
 */
import React, {Component} from "react";
import {Link} from "react-router";
import Utils from "../../common/Utils";
import {articleTYPE,signTYPE} from "../../models/types"
import {Row, Col, Button, Tabs, Card} from "antd";
import moment from "moment";
import BreadcrumbMain from '../breadcrumb/BreadcrumbMain';
import PaginationComponent from "../pagination/PaginationComponent";
import {getParamsFromPage} from '../commons/utils';
import qs from 'qs';
import SearchComponent from "../commons/SearchComponent"
const TabPane = Tabs.TabPane;

export default class ArticleMain extends Component {

    constructor(props) {
        super(props);
        this.state = {
            key: null
        }
    }

    componentDidMount() {
        this.fetchData(this.getBaseQuery());
    }

    componentDidUpdate(prevProps, prevState) {
        if (prevProps.params.category !== this.props.params.category) {
            const query = this.getBaseQuery();
            this.fetchData(query);
        }
    }

    getBaseQuery = (params = {}) => {
        const query = {
            ...params,
            category: this.props.params.category,
        };
        if (query.category) {
            query.category = parseInt(query.category);
        }
        return query;
    };

    fetchData = (query) => {
        this.props.articleService
            .findPage(query)
            .then(_ => {
                Utils.pushLink(`/system/about/${query.category}`);
            })
    };

    renderData = (articlePage) => {

        const user = Utils.getToObject(this.props.sign, signTYPE.SIGN_IN);

        return (articlePage.content || []).map((doc, idx) => {
            return (
                <div style={{background: '#ECECEC', padding: '5px'}} key={idx}>
                    <Card bordered={false}>
                        <Link to={`/system/about/detail/${doc.id}`}>
                            <h3>{doc.title}</h3>
                        </Link>
                        <Row>
                            <Col span={12}><p>{doc.description}</p></Col>
                            <Col span={4}><span>浏览量：{doc.browseCount}</span></Col>
                            <Col span={4}><span>{moment(doc.createDate).format('YYYY-MM-DD')}</span></Col>
                            <Col span={4}>{user.id === 1 ? <Button type="primary" onClick={() => {this.props.articleService.deleteArticle(doc.id);this.props.articleService.findPage({...this.props.location.query,category: this.props.params.category})}}>删除</Button> : null}</Col>
                        </Row>
                    </Card>
                </div>

            )
        })
    };

    renderMenu = (articlePage) => {
        const menuMap = [
            {key: '1', value: '发展历史'},
            {key: '2', value: '教学内容'},
            {key: '3', value: '教师团队'},
            {key: '4', value: '教学成果'}
        ];
        return menuMap.map((obj, idx) => {
                return (
                    <TabPane tab={obj.value} key={obj.key}>
                        {this.renderData(articlePage)}
                    </TabPane>
                )
            }
        )
    };

    pushLink = (key) => {
        const path = '/system/about/' + key;
        Utils.pushLink(path)
    };

    searchControls = (initialValue = {}) => {
        let __date = [];
        if (initialValue.beginDate && initialValue.endDate) {
            __date[0] = moment(initialValue.beginDate, 'YYYY-MM-DD');
            __date[1] = moment(initialValue.endDate, 'YYYY-MM-DD');
        }
        return [{
            type: 'text',
            item: {label: '标题'},
            name: 'title',
            options: {
                initialValue: initialValue.title
            },
        }, {
            type: 'rangeDatePicker',
            item: {label: '发表时间'},
            name: '__date',
            options: {
                initialValue: __date
            },
            props: {
                placeholder: ['开始时间', '结束时间'],
                format: 'YYYY-MM-DD'
            }
        }];
    };

    handleSearch = (value) => {
        const query = this.getBaseQuery();
        if (value.__date) {
            const [beginDate, endDate] = value.__date;
            if (beginDate && endDate) {
                query.beginDate = beginDate.format('YYYY-MM-DD');
                query.endDate = endDate.format('YYYY-MM-DD');
            }
            query.__date = undefined;
        }
        query.title = value.title;
        this.fetchData(query);

    };

    render() {

        const articlePage = Utils.getToObject(this.props.article, articleTYPE.ARTICLE_PAGE);

        const paginationProps = {
            pageSize: articlePage.size || 0,
            currentPage: articlePage.page || 0,
            totalCount: articlePage.totalElements || 0,
            alwaysShow: true,
            onChange: (page, size) => {
                const query = this.getBaseQuery();
                query.page = page;
                query.size = size;
                this.fetchData(query);
            },
        };

        const breadcrumb = [
            {
                name: '首页',
                link: '/'
            }, {
                name: '关于课程',
                link: '/system/about/1'
            }
        ];

        const searchProps = {
            controls: this.searchControls(this.props.location.query),
            onSearch: this.handleSearch
        };


        return (
            <div>
                <BreadcrumbMain breadcrumb={breadcrumb}/>
                <Card bordered={false}>
                    <div style={{margin: `5px 0`}}>
                        <SearchComponent {...searchProps}/>
                    </div>
                </Card>
                <Tabs style={{marginTop: 17}} defaultActiveKey={this.props.params.category} size="default" onChange={this.pushLink}>
                    {this.renderMenu(articlePage)}
                </Tabs>
                <Row>
                    <Col span={2}>
                        <Link to="/system/about/editor/add" query={{category: this.props.params.category}}>
                            <Button style={{margin: '16px 10px'}} type="primary">发表文章</Button>
                        </Link></Col>
                    <Col span={22}><PaginationComponent options={paginationProps}/></Col>
                </Row>
            </div>
        )
    }
}